<template>
  <div class="container">
    <div class="app-container">
      <el-button class="btn-add" size="mini" type="primary" @click="addPermission(0,1)">添加权限</el-button>
      <!-- 加  row-key="id" 就会展示子级 -->
      <el-table :data="list" default-expand-all row-key="id">
        <el-table-column label="名称" prop="name" />
        <el-table-column label="标识" prop="code" />
        <el-table-column label="描述" prop="description" />
        <el-table-column label="操作">
          <template v-slot="{row}">
            <!-- type= text 说明是链接 -->
            <el-button v-if="row.type === 1" size="mini" type="text" @click="addPermission(row.id, row.type)">添加</el-button>
            <el-button size="mini" type="text" @click="editPermission(row.id)">编辑</el-button>
            <el-button size="mini" type="text" @click="delPermission(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 弹层 -->
      <add-comp
        ref="diologRef"
        :show-dialog.sync="showDialog"
        :pid="pid"
        :type="type"
        @success="getPermissionList"
      />
    </div>
  </div>
</template>
<script>
import { getPermissionList, getPermissionDetail, delPermission } from '@/api/permission'
import { transListToTreeData } from '@/utils'
import AddComp from './components/add-comp.vue'
export default {
  name: 'Permission',
  components: { AddComp },
  data() {
    return {
      list: [],
      showDialog: false,
      pid: null,
      type: null
    }
  },
  created() {
    this.getPermissionList()
  },
  methods: {
    // 将列表数据转化成树形结构
    async getPermissionList() {
      this.list = transListToTreeData(await getPermissionList(), 0)
      // console.log(this.list)
    },
    addPermission(id, type) {
      this.pid = id
      this.type = id !== 0 ? 2 : type
      // console.log(this.pid, this.type)
      this.showDialog = true
    },
    async editPermission(id) {
      // console.log(id)
      this.$refs.diologRef.formData = await getPermissionDetail(id)
      this.showDialog = true
    },
    async delPermission(id) {
      try {
        await this.$confirm('确定要删除该数据吗?')
        await delPermission(id)
        this.getPermissionList()
        this.$message.success('删除成功')
      } catch (error) {
        this.$message.error(error)
      }
    }
  }
}
</script>
<style>
.btn-add {
  margin: 10px;
}
</style>
